/// Creator:      gaoruishan
/// CreatDate:    2025-06-17
/// Description:  生命体征相关
Class Nur.MNISV3.Service.Temperature Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// 获取病人在某个时间点的体征数据
/// w ##class(Nur.MNISV3.Service.Temperature).GetTempPatListV4("","2025-06-18","","3","20665","8","2","{""single"":"""",""multiple"":""1""}")
ClassMethod GetTempPatListV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras) As %String
{
    n (episodeId, date, time, wardId, userId, locId, hospitalId, extras,%session)
    s $zt="errGetTempPatListV4"
    s ^GRS("GetTempPatListV4")=$lb(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    // 体征测量时间点列表
    s timePoints=##class(Nur.MNISV3.Service.Temperature).GetTimePoints()
    s nearDateTime= ..GetNearDateTime(date_" "_time)
    s nearDate=$p(nearDateTime," ",1)
    s nearTime=$p(nearDateTime," ",2)
    w nearDateTime,!
    i time="" s time=nearTime //取最近时间
    s obsPats=##class(%ListOfDataTypes).%New()
    i episodeId'="" {//单患者
        // 体征项列表
        s babyFlag=..GetBabyFlag(episodeId)
        s obsItems=##class(Nur.MNISV3.Service.Temperature).GetObsItems(locId,babyFlag,nearTime)
        s patinfo=##class(%ArrayOfDataTypes).%New()
        //基本患者信息
        s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
        s obsData=..GetObsDataObjByDateTime(episodeId,date,time,obsItems)
        d patinfo.SetAt($g(obsData),"obsData")
        s obsTask=..GetObsTaskObj(episodeId,date,"",obsItems,locId)
        d patinfo.SetAt($g(obsTask),"obsTask")
        d obsPats.Insert(patinfo)
    }else {
        //调用纯净版患者列表，
        s patListObj=##class(%ResultSet).%New("Nur.MNISV3.Service.Patient:GetPatList")
        d patListObj.Execute(wardId,userId,"Ward",locId)
        while(patListObj.Next()){
            s patinfo=##class(Nur.MNISV3.Common.Utils).ResultSet(patListObj)
            s episodeId=patListObj.GetDataByName("episodeId")
            // 体征项列表
            s babyFlag=..GetBabyFlag(episodeId)
            s obsItems=##class(Nur.MNISV3.Service.Temperature).GetObsItems(locId,babyFlag,nearTime)
            s obsData=..GetObsDataObjByDateTime(episodeId,date,time,obsItems)
            d patinfo.SetAt($g(obsData),"obsData")
            s obsTask=..GetObsTaskObj(episodeId,date,"",obsItems,locId)
            d patinfo.SetAt($g(obsTask),"obsTask")
            //基本患者信息
            s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
            d obsPats.Insert(patinfo)
        }
    }

    //i (ret'=0) s Msg=ret,msgcode="100212",Status="-1"
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(obsPats),"obsPats")
    d json.SetAt($g(obsItems),"obsItems")
    d json.SetAt($g(timePoints),"timePoints")
    d json.SetAt($g(nearDate),"nearDate")
    d json.SetAt($g(nearTime),"nearTime")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetTempPatListV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 获取病人在某个时间点的体征数据
/// w ##class(Nur.MNISV3.Service.Temperature).GetTempValueV4(
ClassMethod GetTempValueV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras) As %String
{
    n (episodeId, date, time, wardId, userId, locId, hospitalId, extras,%session)
    s $zt="errGetTempValueV4"
    s ^GRS("GetTempValueV4")=$lb(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
    q ##class(Nur.MNISV3.Service.Temperature).GetTempPatListV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
errGetTempValueV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// w ##class(Nur.MNISV3.Service.Temperature).GetTempTaskV4("345","2025-06-19","18:00","8","20665")
ClassMethod GetTempTaskV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras) As %String
{
    n (episodeId, date, time, wardId, userId, locId, hospitalId, extras,%session)
    s $zt="errGetTempTaskV4"
    s ^GRS("GetTempTaskV4")=$lb(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
    q ##class(Nur.MNISV3.Service.Temperature).GetTempPatListV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
errGetTempTaskV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 体征详情
/// w ##class(Nur.MNISV3.Service.Temperature).GetPatTempDetailV4(
ClassMethod GetPatTempDetailV4(episodeId, fromDate, toDate, typeId, id, locId, userId) As %String
{
    n (episodeId,fromDate,toDate,typeId,id,locId,userId,%session)
    s $zt="errGetPatTempDetailV4"
    s ^GRS("GetPatTempDetailV4")=$lb(episodeId, fromDate, toDate, typeId, id,locId,userId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s fromDate=##class(websys.Conversions).DateHtmlToLogical(fromDate)
    s toDate=##class(websys.Conversions).DateHtmlToLogical(toDate)
    s obsPats=##class(%ListOfDataTypes).%New()
    // 体征项列表
    s babyFlag=..GetBabyFlag(episodeId)
    s obsItems=##class(Nur.MNISV3.Service.Temperature).GetObsItems(locId,babyFlag)
    s patinfo=##class(%ArrayOfDataTypes).%New()
    //基本患者信息
    s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
    s obsData=..GetObsDataObjByDateRange(episodeId,fromDate,toDate,obsItems)
    d patinfo.SetAt($g(obsData),"obsData")
    d obsPats.Insert(patinfo)
    
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(obsPats),"obsPats")
    d json.SetAt($g(obsItems),"obsItems") 
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetPatTempDetailV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 保存体征
/// w ##class(Nur.MNISV3.Service.Temperature).SaveTempDataV4("[{""bedCode"":""01"",""episodeID"":""1217"",""name"":""马亭演示"",""obsData"":[{""data"":[{""code"":""temperature"",""color"":null,""value"":""36.5""},{""code"":""breath"",""color"":null,""value"":""33""}],""date"":""2025-06-18"",""time"":""00:00""}],""obsTask"":null,""code"":null,""desc"":null,""episodeId"":null,""method"":null,""num"":null,""object"":null,""select"":false,""selected"":""0""}]","2025-06-18","14:00","{""single"":""1""}","8","20665","3")
ClassMethod SaveTempDataV4(obsPats, date, time, extras, locId, userId, wardId) As %String
{
    n (obsPats, date, time, extras, locId, userId,wardId,%session)
    s $zt="errSaveTempDataV4"
    s ^GRS("SaveTempDataV4")=$lb(obsPats, date, time, extras, locId, userId,wardId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s dateVal=##class(websys.Conversions).DateHtmlToLogical(date)
    s timeVal=##class(websys.Conversions).TimeHtmlToLogical(time)
    s patList=##class(Nur.MNISV3.Common.JSON).Decode(obsPats)
    s extras=##class(Nur.MNISV3.Common.JSON).Decode(extras)
    s single=extras.GetAt("single"),batch=extras.GetAt("batch")
    s patLen=patList.Count()
    f patInd=1:1:patLen {
        s patObj=patList.GetAt(patInd)
        s episodeIdFor=patObj.GetAt("episodeID")
        //检查入院时间和住科时间
        s ret=..CheckAdmission(episodeIdFor,dateVal,timeVal,wardId)
        i (ret'=0) s Msg=ret continue
        s obsData=patObj.GetAt("obsData")
        s obsTimeDataLen=obsData.Count()
        f obsTimeDataInd=1:1:obsTimeDataLen {
            s obsTimeData=obsData.GetAt(obsTimeDataInd)
            s obsDate=obsTimeData.GetAt("date")
            s obsTime=obsTimeData.GetAt("time")
            s obsDate=##class(Nur.Tools).ABCS(##class(Nur.Tools).Date(obsDate),dateVal,obsDate'="")
            s obsTime=##class(Nur.Tools).ABCS(##class(Nur.Tools).Time(obsTime),timeVal,obsTime'="")
            s data=obsTimeData.GetAt("data")
            s len=data.Count()
            f ind=1:1:len {
                s obj=data.GetAt(ind)
                s code=obj.GetAt("code")
                s value=obj.GetAt("value")
                s blankLabel=..BlankLabel(episodeIdFor,code,obsDate)
                continue:($p(blankLabel,"^"))&&(value=$p(blankLabel,"^",2))
                //RapidAssembly: Rapid快速 Assembly组装成一个obj, 第一个参数“,”分割 和后面顺序对应
                s tObj=##class(Nur.Tools).RapidAssembly("code,value,time",code,value,$zt(obsTime,2))
                //AppendSet: 将第二个obj添加到list中,第一个参数可以空
                s sbd=##class(Nur.Tools).AppendSet(,tObj)
                s ^GRS("SaveObsDataByDay")=$lb(episodeIdFor,sbd,userId,$zd(obsDate,3),locId,wardId)
                s ret=##Class(Nur.NIS.Service.VitalSign.Temperature).SaveObsDataByDay(episodeIdFor,sbd,userId,$zd(obsDate,3),locId,wardId)
                i (ret'=0) s Msg=ret,Status="-1"
            }
        }
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errSaveTempDataV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 查询事件
/// w ##class(Nur.MNISV3.Service.Temperature).GetPatEventsV4("","2025-06-16","14:32","3","20665","8","2","{""single"":"""",""multiple"":""1""}")
ClassMethod GetPatEventsV4(episodeId, date, time, wardId, userId, locId, hospitalId, extras)
{
    n (episodeId, date, time,wardId,userId,locId, hospitalId, extras,%session)
    s $zt="errGetPatEventsV4"
    s ^GRS("GetPatEventsV4")=$lb(episodeId, date, time,wardId,userId,locId, hospitalId, extras)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s eventItems=##class(%ListOfDataTypes).%New()
    s eventPats=##class(%ListOfDataTypes).%New()
    //患者事件类别
    s rs=##class(%ResultSet).%New("Nur.NIS.Service.VitalSign.Event:FindEventTypeList")
    d rs.Execute("",hospitalId)
    //将resultSet组装到List对象中
    s eventItems=##class(Nur.MNISV3.Common.Utils).ResultSetToList(rs)
  
    s eventData=##class(%ListOfDataTypes).%New()
    i episodeId'="" { //单患者
        s patinfo=##class(%ArrayOfDataTypes).%New()
        //基本患者信息
        s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
        d eventPats.Insert(patinfo)
    }else {
        //调用纯净版患者列表，
        s patListObj=##class(%ResultSet).%New("Nur.MNISV3.Service.Patient:GetPatList")
        d patListObj.Execute(wardId,userId,"Ward",locId)
        while(patListObj.Next()){
           s patinfo= ##class(Nur.MNISV3.Common.Utils).ResultSet(patListObj)
           s episodeId=patListObj.GetDataByName("episodeId")
           w episodeId,!
           //获取体温单事件
           s patEventsObj=##class(%ResultSet).%New("Nur.NIS.Service.VitalSign.Event:FindTempEvent")
           d patEventsObj.Execute(episodeId)
           //将resultSet组装到List对象中
           s eventData= ##class(Nur.MNISV3.Common.Utils).ResultSetToList(patEventsObj)
           d patinfo.SetAt($g(eventData),"eventData")
           //基本患者信息
           s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
           d eventPats.Insert(patinfo)
        }
    }

    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(eventItems),"eventItems") 
    d json.SetAt($g(eventPats),"eventPats")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetPatEventsV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 保存事件
/// w ##class(Nur.MNISV3.Service.Temperature).SaveEventV4(
ClassMethod SaveEventV4(episodeId, date, time, typeId, id, locId, userId) As %String
{
    n (episodeId,date,time,typeId,id,locId,userId,%session)
    s $zt="errSaveEventV4"
    s ^GRS("SaveEventV4")=$lb(episodeId, date, time, typeId, id,locId,userId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s dateVal=##class(websys.Conversions).DateHtmlToLogical(date)
    s timeVal=##class(websys.Conversions).TimeHtmlToLogical(time)
    s ret=##class(Nur.NIS.Service.VitalSign.Event).InsertTempEvent(episodeId,$zd(dateVal,3),$zt(timeVal,1),typeId,userId,id,locId)
    i (ret'=0) s Msg=ret,msgcode="100212",Status="-1"
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errSaveEventV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 作废事件
/// w ##class(Nur.MNISV3.Service.Temperature).DelEventV4(
ClassMethod DelEventV4(id, locId, userId) As %String
{
    n (id,locId,userId,%session)
    s $zt="errDelEventV4"
    s ^GRS("DelEventV4")=$lb(id,locId,userId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    q:(id="") ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson("请选择一条记录","100021","-1")
    s ret=##class(Nur.NIS.Service.VitalSign.Event).VoidTempEvent(id,userId,locId)
    i (ret'=0) s Msg=ret,msgcode="100212",Status="-1"
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errDelEventV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 直接取PC配置，如果有必要再单独复制一份
ClassMethod GetObsItems(locId, babyFlag, timePoint, isFirstTrans) As %String
{
    n (locId,babyFlag,timePoint,isFirstTrans,%session)
    s obsItems=##class(Nur.NIS.Service.VitalSign.Temperature).GetTempConfig(locId,$g(babyFlag),$g(timePoint),$g(isFirstTrans))
    s obsItemLen=obsItems.Count()
    f obsItemInd=1:1:obsItemLen {
        s obsItem=obsItems.GetAt(obsItemInd) 
        s desc=obsItem.GetAt("desc")
        s desc=$replace(desc,"(","（")
        i (desc["（") {
            s desc=$p(desc,"（")
            d obsItem.SetAt(desc,"desc")
        }
    } 
    q obsItems
}

/// 体征测量时间点列表
/// w ##class(Nur.JSON).Encode(##class(Nur.MNISV3.Service.Temperature).GetTimePoints())
ClassMethod GetTimePoints() As %String
{
    n (%session)
    s list=##class(%ListOfDataTypes).%New()
    s timePoints=##class(Nur.NIS.Service.VitalSign.MRCObservationItem).getVSGenelConfig().GetAt("timePoint")
    s l=$l(timePoints,",")
    f i=1:1:l {
        s timePoint=$p(timePoints,",",i)
        s obj=##class(%ArrayOfDataTypes).%New()
        d obj.SetAt(timePoint,"time")
        d list.Insert(obj)
    }
    q list
}

/**
 * @author      EH
 * @desc        传time查全日，否则当时
 */
ClassMethod GetObsTaskObj(episodeId, date, time, obsItems, locId) As %String
{
    n (episodeId,date,time,obsItems,locId,%session)
    s getInfoObj=##class(%ListOfDataTypes).%New()
    s timePoint=$s(time'="":$zt(##class(Nur.Tools).Time(time),2),1:"")
    s getDateObj=$$getObsTaskObj(episodeId,date,locId)
    i ($isobject(getDateObj)) {
        i (timePoint'="") {
            d setObsTaskObj(getInfoObj,getDateObj,episodeId,date,timePoint,obsItems)
        } else {
            s timePoint=""
            while (1) {
                s timePoint=getDateObj.Next(timePoint)
                q:(timePoint="")
                d setObsTaskObj(getInfoObj,getDateObj,episodeId,date,timePoint,obsItems)
            }
        }
    }
    q getInfoObj
setObsTaskObj(getInfoObj,getDateObj,episodeId,date,timePoint,obsItems)
    n (getInfoObj,getDateObj,episodeId,date,timePoint,obsItems)
    s getDateTimeObj=getDateObj.GetAt(timePoint)
    i ($isobject(getDateTimeObj)) {
        s getDateTimePatObj=getDateTimeObj.GetAt(episodeId)
        s getInfoPatTimeDataObj=##class(%ListOfDataTypes).%New()
        i ($isobject(getDateTimePatObj)) {
            s obsItemLen=obsItems.Count()
            f obsItemInd=1:1:obsItemLen {
                s obsItem=obsItems.GetAt(obsItemInd) 
                s code=obsItem.GetAt("code")
                i (getDateTimePatObj.IsDefined(code)) {
                    s getInfoPatTimeItemObj=##class(%ArrayOfDataTypes).%New()
                    d getInfoPatTimeItemObj.SetAt(code,"code")
                    d getInfoPatTimeDataObj.Insert(getInfoPatTimeItemObj)
                }
            }
        }
        i (getInfoPatTimeDataObj.Count()) {
            s dateDes=$zd(##class(Nur.Tools).Date(date),3)
            s timeDes=$zt(##class(Nur.Tools).Time(timePoint),2)
            s getInfoPatTimeObj=##class(%ArrayOfDataTypes).%New()
            d getInfoPatTimeObj.SetAt(dateDes,"date")
            d getInfoPatTimeObj.SetAt(timeDes,"time")
            d getInfoPatTimeObj.SetAt(getInfoPatTimeDataObj,"data")
            d getInfoObj.Insert(getInfoPatTimeObj)
        }
    }
    q
getObsTaskObj(episodeId,date,locId)
    n (episodeId,date,locId,%session)
    try {
        s json=##class(Nur.NIS.Service.VitalSign.Temperature).GetTempDateMeasureByDayEncode(episodeId,date,locId,1)
    } catch {
        s json=""
    }
    s ^GRS("GetTempDateMeasureByDayEncode")=json
    ;;;时间作为key暂处理
    s obj=##class(%ArrayOfDataTypes).%New()
    i ('$isobject(json)) {
        s conv=json
        s i=$f(conv,":")
        while (i>0) {
            s prev=$e(conv,i-2)
            s next=$e(conv,i)
            i (prev'="""")&&(next'="""") s $e(conv,i-1)=";"
            s i=$f(conv,":",i)
        }
        s obj=##class(%ArrayOfDataTypes).%New()
        s dec=##class(Nur.MNIS.Common.JSON).Decode(conv)
        i ($isobject(dec)) {
            s key=dec.Next("")
            while (key'="") {
                s timePoint=$zt(##class(Nur.Tools).Time($replace(key,";",":")),2)
                d obj.SetAt(dec.GetAt(key),timePoint)
                s key=dec.Next(key)
            }
        }
    }
    q obj
}

/**
 * @author      EH
 * @desc        检查入院时间和住科时间
 */
ClassMethod CheckAdmission(episodeId, date, time, wardId) As %String
{
    n (episodeId,date,time,wardId,%session)
    s dateVal=##class(websys.Conversions).DateHtmlToLogical(date)
    s timeVal=##class(websys.Conversions).TimeHtmlToLogical(time)
    s dateTimeVal=dateVal*86400+timeVal
    s curDate=$p($h,",",1)
    s curTime=$p($h,",",2)
    s curDateTime=curDate*86400+curTime
    q:(dateTimeVal-curDateTime-$zth("12:00")>0) "-1^记录时间不能提前12小时"
    s admDate=$p($g(^PAADM(episodeId,"DHC")),"^",31)
    s admTime=$p($g(^PAADM(episodeId,"DHC")),"^",32)
    s admDateTime=admDate*86400+admTime
    q:(dateTimeVal-admDateTime+$zth("00:01")<0) "-1^记录时间不能早于入院时间"
    k transStartArr
    s lastLocId="",lastWardId=""
    s chl=0 f  s chl=$o(^PAADM(episodeId,"TRANS",chl)) q:(chl="")  d
    .s transLocId=$p($g(^PAADM(episodeId,"TRANS",chl)),"^",6)
    .s transWardId=$p($g(^PAADM(episodeId,"TRANS",chl)),"^",9)
    .s transBedId=$p($g(^PAADM(episodeId,"TRANS",chl)),"^",8)
    .s transDate=$p($g(^PAADM(episodeId,"TRANS",chl)),"^",1)
    .s transTime=$p($g(^PAADM(episodeId,"TRANS",chl)),"^",2)
    .i (transLocId'="") d
    ..i (lastLocId="")||(transLocId'=lastLocId) d
    ...s i=$o(transStartArr(""),-1)+1
    ...s transStartArr(i)=$lb(transLocId,transDate,transTime)
    ...s lastLocId=transLocId,lastWardId=""
    .i (transWardId'="") d
    ..i (lastWardId="")||(transWardId'=lastWardId) d
    ...s j=$o(transStartArr(i,""),-1)+1
    ...s transStartArr(i,j)=$lb(transWardId,transDate,transTime)
    ...s lastWardId=transWardId
    .i (transBedId'="") d
    ..s transBedWardId=$p(transBedId,"||")
    ..i (lastLocId="") d
    ...s i=$o(transStartArr(""),-1)+1
    ...s transStartArr(i)=$lb("",transDate,transTime)
    ..i (lastWardId="") d
    ...s j=$o(transStartArr(i,""),-1)+1
    ...s transStartArr(i,j)=$lb(transBedWardId,transDate,transTime)
    ..s k=$o(transStartArr(i,j,""),-1)+1
    ..s transStartArr(i,j,k)=$lb(transBedId,transDate,transTime)
    k transPeriodArr
    s a="",b=""
    s i="" f  s i=$o(transStartArr(i)) q:(i="")  d
    .s j="" f  s j=$o(transStartArr(i,j)) q:(j="")  d
    ..s k=$o(transStartArr(i,j,""))
    ..i (k="") k transStartArr(i,j)
    .s j=$o(transStartArr(i,""))
    .i (j="") k transStartArr(i)
    s i="" f  s i=$o(transStartArr(i)) q:(i="")  d
    .i (b'="") d
    ..s $li(transPeriodArr(b),4)=$lg(transStartArr(i),2)
    ..s $li(transPeriodArr(b),5)=$lg(transStartArr(i),3)
    .s j="" f  s j=$o(transStartArr(i,j)) q:(j="")  d
    ..s a=$o(transPeriodArr(""),-1)+1
    ..s transPeriodArr(a)=transStartArr(i,j)
    ..i (b'="") d
    ...s $li(transPeriodArr(b),4)=$lg(transStartArr(i,j),2)
    ...s $li(transPeriodArr(b),5)=$lg(transStartArr(i,j),3)
    ..s b=a
    s inPeriod=0
    s i="" f  s i=$o(transPeriodArr(i)) q:(i="")||(inPeriod=2)  d
    .s transWardId=$lg(transPeriodArr(i),1)
    .q:(transWardId'=wardId)
    .s inPeriod=0
    .s transStartDate=$lg(transPeriodArr(i),2)
    .s transStartTime=$lg(transPeriodArr(i),3)
    .s transStartDateTime=transStartDate*86400+transStartTime
    .q:(dateTimeVal-transStartDateTime+$zth("00:01")<0)
    .s inPeriod=1
    .s transEndDate=$lg(transPeriodArr(i),4)
    .s transEndTime=$lg(transPeriodArr(i),5)
    .s transEndDateTime=transEndDate*86400+transEndTime
    .q:(transEndDateTime>0)&&(dateTimeVal-transEndDateTime-$zth("00:01")>0)
    .s inPeriod=2
    q:(inPeriod=0) "-1^记录时间不能早于入科时间"
    q:(inPeriod=1) "-1^记录时间不能晚于出科时间"
    q 0
}

ClassMethod GetNearDateTime(value) As %String
{
    n (value,%session)
    i (value[" ") s today=$p(value," "),now=$p(value," ",2)
    e  i (value'="") s today="",now=value
    e  s today="",now=""
    s today=$s(today="":$p($h,",",1),1:##class(websys.Conversions).DateHtmlToLogical(today))
    s now=$s(now="":$p($h,",",2),1:##class(websys.Conversions).TimeHtmlToLogical(now))
    s halfRange=$zth("02:00"),day=$zth("23:00")+$zth("01:00"),date=today,time=$zt(now,2)
    s timePoints=##class(Nur.NIS.Service.VitalSign.MRCObservationItem).getVSGenelConfig().GetAt("timePoint")
    s l=$l(timePoints,","),match=0
    f i=1:1:l {
        s timePoint=$p(timePoints,",",i)
        s timeValue=$zth(timePoint,2)
        s leftMargin=timeValue-halfRange
        s rightMargin=timeValue+halfRange
        i (leftMargin<0) {
            s leftMargin=leftMargin+day
            i (now'<leftMargin) s match=1,date=today+1
            e  i (now<rightMargin) s match=1
        } elseif (rightMargin'<day) {
            s rightMargin=rightMargin-day
            i (now'<leftMargin) s match=1
            e  i (now<rightMargin) s match=1,date=today-1
        } else {
            i (now'<leftMargin)&(now<rightMargin) s match=1
        }
        i ('match) continue
        s time=timePoint,i=l
    }
    q $zd(date,3)_" "_time
}

/// 获取某日期范围的体征数据： fromDate, toDate
ClassMethod GetObsDataObjByDateRange(episodeId, fromDate, toDate, obsItems) As %String
{
    n (episodeId,fromDate,toDate,obsItems,%session)
    s stdate=##class(websys.Conversions).DateHtmlToLogical(fromDate)
    s eddate=##class(websys.Conversions).DateHtmlToLogical(toDate)
    s dataList=##class(%ListOfDataTypes).%New()
    s mradmId=$p($g(^PAADM(episodeId)),"^",61)
    q:(mradmId="") dataList
    s dateFor=stdate-1 f  s dateFor=$o(^MR(mradmId,"OBS",0,"DateTime",dateFor)) q:(dateFor="")||(dateFor>eddate)  d
    .s timeFor="" f  s timeFor=$o(^MR(mradmId,"OBS",0,"DateTime",dateFor,timeFor)) q:(timeFor="")  d
    ..s dataListFor=..GetObsDataObjByDateTime(episodeId,dateFor,timeFor,obsItems)
    ..q:(dataListFor.Count()=0)
    ..s dataObjFor=dataListFor.GetAt(1)
    ..d dataList.Insert(dataObjFor)
    q dataList
}

/// 获取某日期 时间点的体征数据：date, time
ClassMethod GetObsDataObjByDateTime(episodeId, date, time, obsItems) As %String
{
    n (episodeId,date,time,obsItems,%session)
    s dateVal=##class(websys.Conversions).DateHtmlToLogical(date)
    s timeVal=##class(websys.Conversions).TimeHtmlToLogical(time)
    s dataList=##class(%ListOfDataTypes).%New()
    s dataObj=##class(%ArrayOfDataTypes).%New()
    s dataObsList=##class(%ListOfDataTypes).%New()
    d dataObj.SetAt($zd(dateVal,3),"date")
    d dataObj.SetAt($zt(timeVal,2),"time")
    d dataObj.SetAt(dataObsList,"data")
    d dataList.Insert(dataObj)
    s obsItemLen=obsItems.Count()
    f obsItemInd=1:1:obsItemLen {
        s obsItem=obsItems.GetAt(obsItemInd) 
        s code=obsItem.GetAt("code")
        s value=..GetObsValue(episodeId,code,dateVal,timeVal)
        continue:(value="")
        s obj=##class(%ArrayOfDataTypes).%New()
        d obj.SetAt(code,"code")
        d obj.SetAt(value,"value")
        d dataObsList.Insert(obj)
    }
    q dataList
}

ClassMethod GetObsValue(episodeId, code, date, time) As %String
{
    n (episodeId,code,date,time,%session)
    s mradmId=$p($g(^PAADM(episodeId)),"^",61)
    s obsItemId=..getObsIDByCode(code)  
    q:(mradmId="")||(obsItemId="") ""
    s dateVal=##class(websys.Conversions).DateHtmlToLogical(date)
    s timeVal=##class(websys.Conversions).TimeHtmlToLogical(time)
    s blankLabel=..BlankLabel(episodeId,code,date)
    q:($p(blankLabel,"^")) $p(blankLabel,"^",2)
    s chl=$o(^MR(mradmId,"OBS",0,"Item",obsItemId,dateVal,timeVal,""),-1)
    i (chl'="") s value=$p($g(^MR(mradmId,"OBS",chl)),"^",2)
    q $g(value)
}

ClassMethod getObsIDByCode(code) [ Private ]
{
    s hospitalID=##class(Nur.NIS.Common.Utils).GetHospitalID(##class(Nur.NIS.Common.ConstVal).#TABLEOBS)
    s rtn=""
    s itemID="" f  s itemID=$o(^MRC("OBITM",0,"HOSPCode",hospitalID,$$$ALPHAUP(code),"")) q:(itemID="")!(rtn'="")  d
    #;.q:##class(Nur.NIS.Common.Utils).DataAccessFlag("MRC_ObservationItem",itemID)="N"
    .s rtn=itemID
    q rtn
}

ClassMethod BlankLabel(episodeId, code, date) As %String
{
    s blankLabel=code[##class(Nur.NIS.Common.ConstVal).#BlankTitleSymbols
    i (blankLabel) s value=..getlabel(episodeId,code,date)
    q blankLabel_"^"_$g(value)
}

ClassMethod getlabel(adm, code, date) [ Private ]
{
    s admDateTime=##class(Nur.NIS.Service.VitalSign.Event).PACInPatDateBed(adm)
    s admDate=$p(admDateTime,"^",1)
    s admDate=##class(websys.Conversions).DateHtmlToLogical(admDate)
    //Admission date
    i admDate="" s admDate=$p(^PAADM(adm),"^",6)
    s itemDesc=""
    q:(adm="")||(admDate="")||(admDate=0) itemDesc 
    s date=##class(websys.Conversions).DateHtmlToLogical(date)
    q:date<admDate itemDesc
    s compar=date-admDate
    s staDate=date-(compar-(7*(compar\7)))
    s endDate=staDate+6
    s mrAdmID=$P(^PAADM(adm),"^",61)
    i code'["Title" d
    .s itemID=..getObsIDByCode(code_"Title") //$o(^MRC("OBITM",0,"Code",$$$ALPHAUP(code_"Title"),""))
    e  s itemID=..getObsIDByCode(code) //$o(^MRC("OBITM",0,"Code",$$$ALPHAUP(code),""))
    q:itemID="" itemDesc
    s obsID=""
    d GetBlankTitleVal
    i (obsID="")&&(itemDesc="")&&($p($g(^MRC("OBITM",itemID)),"^",32)="Y") { // 是否延续空白栏标题到下一页（下周）
        s staDate=staDate-7
        s endDate=endDate-7
        i endDate>admDate {
            d GetBlankTitleVal
        }
    }
    q itemDesc
GetBlankTitleVal
    f ordSttDate=staDate:1:endDate
    {
        s time="" f  s time=$o(^MR(mrAdmID,"OBS",0,"Item",itemID,ordSttDate,time)) q:(time="")||(itemDesc'="")  d
        .s obsID=$o(^MR(mrAdmID,"OBS",0,"Item",itemID,ordSttDate,time,""))
        .q:obsID=""
        .s itemDesc=$P(^MR(mrAdmID,"OBS",obsID),"^",2)
        #;.i itemDesc'="" s itemDesc=$p(itemDesc,"(",1)  ;项目要求只在选择的时候显示单位,显示时不显示单位
    }
    q
}

ClassMethod GetBabyFlag(episodeId) As %String
{
    n (episodeId)
    s motherEpisodeId=$p($g(^PAADM(episodeId)),"^",75) 
    i (motherEpisodeId'="") s babyFlag=1
    q +$g(babyFlag)
}

}
